package com.zhj.interview;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author zhj
 */
public class Test04 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        long start = System.currentTimeMillis();
        int result = sum();
        System.out.println("异步执行结果为：" + result);
        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + "ms");

        // 方式1
        long start1 = System.currentTimeMillis();
        FutureTask<Integer> task1 = new FutureTask<>(new Callable() {
            @Override
            public Integer call() throws Exception {
                return sum();
            }
        });
        new Thread(task1).start();
        System.out.println("方式一：");
        System.out.println("异步执行结果为：" + task1.get());
        System.out.println("使用时间：" + (System.currentTimeMillis() - start1) + "ms");

        // 方式2
        long start2 = System.currentTimeMillis();
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        //我们主要看如下代码
        Future future = executorService.submit(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                return sum();
            }
        });
        FutureTask<Integer> task2 = new FutureTask(new Callable() {
            @Override
            public Integer call() throws Exception {
                return sum();
            }
        });
        executorService.submit(task2);
        Integer result2 = task2.get();
        System.out.println("方式二：");
        System.out.println("异步执行结果为：" + result2);
        System.out.println("使用时间：" + (System.currentTimeMillis() - start2) + "ms");
    }

    private static int sum(){
        int sum = fibo(40);
        return sum;
    }

    private static int fibo(int a){
        if (a < 2) {
            return 1;
        }
        return fibo(a-1) + fibo(a-2);
    }
}
